package org.sunxin.ch02.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;

import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * 功能说明:
 *
 * Copyright (C)2002－2007 福建鑫诺.All rights reserved. 
 * 
 * WelcomeServlet.java
 *
 * Original Author: 徐金鹏   创建日期:Sep 5, 2008  时间: 3:46:08 PM
 */
public class WelcomeServlet extends HttpServlet {
	private String greeting;
	private String strteString;
	private String appName;
	private Set set  = new HashSet<String>();
	public void init() {
		/**
		 * 我们调用getInitParameter()方法得到初始化参数greeting的值，这个调用和第18行注释的代码是等价的。
		 * 从 HttpServlet继承的getInitParameter()方法实际上也是调用ServletConfig对象的
		 *  getInitParameter()方法来得到初始化参数的
		 */
		greeting = getInitParameter("greeting");
		// greeting = getServletConfig().getInitParameter("greeting");
		
		//获取servlet上下文 中的 初始化参数
		//strteString  = getInitParameter("paramtest");
		strteString=getServletConfig().getServletContext().getInitParameter("paramtest");
		//获取应用程序名称  web.xml文件中
		appName = getServletConfig().getServletContext().getServletContextName();
		/**
		 * /index.jsp:/welcome.html:/success.html:/WEB-INF/:/OutputInfoServlet.html:/login.html:/META-INF/:
		 */
		//获取资源名称 目录 WebRoot下面的文件和目录(不包含目录下面的 文件) 本列使用":"分割开
		set = getServletConfig().getServletContext().getResourcePaths("/");
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		String username = req.getParameter("username");
		String str="";
		Iterator itr = set.iterator();
		while (itr.hasNext()) {
			String strTmp = (String) itr.next();
			if (!strTmp.equals("")) {
				str = str + strTmp + ":";	
			}
			
		}
//		for (int i = 0; i < set.size() -1; i++) {
//			str = str + set.iterator().next().toString();
//			
//		}
		
		 
		String welcomeInfo =str + "  "+ greeting + ", " + username + ":context-param :" + strteString + ":app name :" + appName;

		resp.setContentType("text/html");

		PrintWriter out = resp.getWriter();

		out.println("");
		out.println("");
		out.println(welcomeInfo);
		out.println("");
		out.close();
	}
	//将客户端的 post方法 调用 doget方法得到返回结果
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}
